@{
    Layout = null;
}
<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<script src="~/scripts/jquery-3.4.1.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>

<style>
    .layui-card {
        margin: 5px;
    }
    .layui-form {
        padding: 20px;
    }
    .layui-input-block {
        margin-right: 20px;
    }
</style>

<div class="layui-card">
    <div class="layui-card-header">编辑销售订单</div>
    <div class="layui-card-body">
        <form class="layui-form" lay-filter="component-form-element">
            <input type="hidden" name="id" value="@ViewBag.Id" />
            <div class="layui-row layui-col-space10 layui-form-item">
                <div class="layui-col-lg6">
                    <label class="layui-form-label">订单编码：</label>
                    <div class="layui-input-block">
                        <input type="text" id="orderCode" name="orderCode" lay-verify="required" readonly class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg6">
                    <label class="layui-form-label">订单名称：</label>
                    <div class="layui-input-block">
                        <input type="text" name="orderName" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space10 layui-form-item">
                <div class="layui-col-lg6">
                    <label class="layui-form-label">客户编码：</label>
                    <div class="layui-input-block">
                        <input type="text" name="customerCode" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input" style="width: calc(100% - 30px); display: inline-block;">
                        <i class="layui-icon layui-icon-search" style="margin-left: 5px; cursor: pointer;" id="searchCustomer"></i>
                    </div>
                </div>
                <div class="layui-col-lg6">
                    <label class="layui-form-label">客户名称：</label>
                    <div class="layui-input-block">
                        <input type="text" name="customerName" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space10 layui-form-item">
                <div class="layui-col-lg6">
                    <label class="layui-form-label">订货日期：</label>
                    <div class="layui-input-block">
                        <input type="text" name="orderDate" id="orderDate" lay-verify="required" placeholder="请选择" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg6">
                    <label class="layui-form-label">交货日期：</label>
                    <div class="layui-input-block">
                        <input type="text" name="deliveryDate" id="deliveryDate" lay-verify="required" placeholder="请选择" autocomplete="off" class="layui-input">
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space10 layui-form-item">
                <div class="layui-col-lg6">
                    <label class="layui-form-label">结算方式：</label>
                    <div class="layui-input-block">
                        <select name="settlementMethod" lay-verify="required">
                            <option value="">请选择结算方式</option>
                            <option value="月结30天">月结30天</option>
                            <option value="月结45天">月结45天</option>
                            <option value="月结60天">月结60天</option>
                            <option value="代收货款">代收货款</option>
                            <option value="转贝宝">转贝宝</option>
                            <option value="店面收现金">店面收现金</option>
                            <option value="转账">转账</option>
                        </select>
                    </div>
                </div>
                <div class="layui-col-lg6">
                    <label class="layui-form-label">订单类别：</label>
                    <div class="layui-input-block">
                        <select name="orderCategory" lay-verify="required">
                            <option value="">请选择订单类别</option>
                            <option value="客户订单">客户订单</option>
                            <option value="备货订单">备货订单</option>
                            <option value="样品订单">样品订单</option>
                            <option value="退货订单">退货订单</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-row layui-col-space10 layui-form-item">
                <div class="layui-col-lg6">
                    <label class="layui-form-label">业务员：</label>
                    <div class="layui-input-block">
                        <input type="text" name="salesperson" lay-verify="required" placeholder="请输入" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-col-lg6">
                    <label class="layui-form-label">质量要求：</label>
                    <div class="layui-input-block">
                        <select name="qualityRequirement" lay-verify="required">
                            <option value="">请选择质量等级</option>
                            <option value="A">A</option>
                            <option value="AA">AA</option>
                            <option value="AAA">AAA</option>
                            <option value="AAAA">AAAA</option>
                            <option value="AAAAA">AAAAA</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">备注：</label>
                <div class="layui-input-block">
                    <textarea name="remark" placeholder="请输入" class="layui-textarea"></textarea>
                </div>
            </div>
            
            <!-- 产品明细表格 -->
            <div class="layui-form-item">
                <label class="layui-form-label">产品明细：</label>
                <div class="layui-input-block">
                    <button type="button" class="layui-btn layui-btn-normal" id="addProduct">添加产品</button>
                    <table class="layui-table" id="productTable">
                        <thead>
                            <tr>
                                <th>产品编码</th>
                                <th>产品名称</th>
                                <th>材质</th>
                                <th>颜色</th>
                                <th>订货数量</th>
                                <th>单位</th>
                                <th>金额</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>

            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit lay-filter="component-form-element">提交</button>
                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script type="text/html" id="productRowTemplate">
    <tr>
        <td>
            <div class="layui-input-inline" style="width: calc(100% - 30px);">
                <input type="text" name="productCode" class="layui-input" lay-verify="required" readonly>
            </div>
            <i class="layui-icon layui-icon-search" style="margin-left: 5px; cursor: pointer;" onclick="selectProduct(this)"></i>
        </td>
        <td>
            <input type="text" name="productName" class="layui-input" lay-verify="required" readonly>
        </td>
        <td>
            <input type="text" name="material" class="layui-input">
        </td>
        <td>
            <input type="text" name="color" class="layui-input">
        </td>
        <td>
            <input type="number" name="orderQuantity" class="layui-input" lay-verify="required|number" min="1">
        </td>
        <td>
            <input type="text" name="unitQuantity" class="layui-input" lay-verify="required">
        </td>
        <td>
            <input type="number" name="amount" class="layui-input" lay-verify="required|number" step="0.01" min="0">
        </td>
        <td>
            <button type="button" class="layui-btn layui-btn-danger layui-btn-xs delete-row">删除</button>
        </td>
    </tr>
</script>

<script>
    layui.use(['form', 'laydate', 'table'], function () {
        var form = layui.form
            , laydate = layui.laydate
            , table = layui.table;

        //日期
        laydate.render({
            elem: '#orderDate',
            type: 'date',
            format: 'yyyy-MM-dd'
        });
        laydate.render({
            elem: '#deliveryDate',
            type: 'date',
            format: 'yyyy-MM-dd'
        });

        // 加载订单数据
        var id = $('input[name="id"]').val();
        if(id) {
            $.get('/SalesOrder/GetById', { id: id }, function(res) {
                if(res.code === 0 && res.data) {
                    var data = res.data;
                    
                    // 格式化日期
                    var formatDate = function(dateStr) {
                        if (!dateStr) return '';
                        var date = new Date(dateStr);
                        return date.getFullYear() + '-' + 
                               String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                               String(date.getDate()).padStart(2, '0');
                    };

                    // 设置表单数据
                    form.val('component-form-element', {
                        'orderCode': data.orderCode,
                        'orderName': data.orderName,
                        'customerCode': data.customerCode,
                        'customerName': data.customerName,
                        'orderDate': formatDate(data.orderDate),
                        'deliveryDate': formatDate(data.deliveryDate),
                        'settlementMethod': data.settlementMethod,
                        'orderCategory': data.orderCategory,
                        'salesperson': data.salesperson,
                        'qualityRequirement': data.qualityRequirement,
                        'remark': data.remark
                    });

                    // 加载产品明细
                    if(data.products && data.products.length > 0) {
                        data.products.forEach(function(product) {
                            var template = $('#productRowTemplate').html();
                            var $tr = $(template);
                            $tr.find('input[name="productCode"]').val(product.productCode);
                            $tr.find('input[name="productName"]').val(product.productName);
                            $tr.find('input[name="material"]').val(product.material);
                            $tr.find('input[name="color"]').val(product.color);
                            $tr.find('input[name="orderQuantity"]').val(product.orderQuantity);
                            $tr.find('input[name="unitQuantity"]').val(product.unitQuantity);
                            $tr.find('input[name="amount"]').val(product.amount);
                            $('#productTable tbody').append($tr);
                        });
                    }
                    form.render();
                } else {
                    layer.msg(res.msg || '加载数据失败', {icon: 2});
                }
            });
        }

        // 客户选择
        $('#searchCustomer').on('click', function() {
            layer.open({
                type: 1,
                title: '选择客户',
                area: ['800px', '500px'],
                content: '<table id="customerTable" lay-filter="customerTable"></table>',
                success: function() {
                    table.render({
                        elem: '#customerTable',
                        url: '/SalesOrder/GetCustomerList',
                        method: 'get',
                        cols: [[
                            {field: 'customerCode', title: '客户编码', width: 120},
                            {field: 'customerName', title: '客户名称', width: 200},
                            {title: '操作', width: 100, templet: function() {
                                return '<a class="layui-btn layui-btn-xs" lay-event="select">选择</a>';
                            }}
                        ]],
                        page: true
                    });

                    table.on('tool(customerTable)', function(obj) {
                        if(obj.event === 'select') {
                            $('input[name="customerCode"]').val(obj.data.customerCode);
                            $('input[name="customerName"]').val(obj.data.customerName);
                            layer.closeAll();
                        }
                    });
                }
            });
        });

        // 添加产品行
        $('#addProduct').on('click', function() {
            var customerCode = $('input[name="customerCode"]').val();
            if (!customerCode) {
                layer.msg('请先选择客户', {icon: 2});
                return;
            }
            
            var template = $('#productRowTemplate').html();
            $('#productTable tbody').append(template);
            form.render();
        });

        // 删除产品行
        $(document).on('click', '.delete-row', function() {
            $(this).closest('tr').remove();
        });

        // 修改产品选择相关代码
        window.selectProduct = function(element) {
            var tr = $(element).closest('tr');
            // 打开新页面
            window.selectCallback = function(data) {
                tr.find('input[name="productCode"]').val(data.productCode);
                tr.find('input[name="productName"]').val(data.productName);
                tr.find('input[name="material"]').val(data.material || '');
                tr.find('input[name="color"]').val(data.color || '');
                tr.find('input[name="unitQuantity"]').val(data.unit || '');
                // 如果有单价，可以设置默认金额
                if(data.unitPrice) {
                    var quantity = tr.find('input[name="orderQuantity"]').val() || 1;
                    tr.find('input[name="amount"]').val((data.unitPrice * quantity).toFixed(2));
                }
            };
            
            layer.open({
                type: 2,
                title: '产品选择',
                area: ['100%', '100%'],
                content: '/SalesOrder/ProductList'
            });
        };

        // 数量变化时自动计算金额
        $(document).on('change', 'input[name="orderQuantity"]', function() {
            var tr = $(this).closest('tr');
            var quantity = $(this).val() || 0;
            var amount = tr.find('input[name="amount"]').val() || 0;
            if(amount > 0) {
                var unitPrice = amount / (tr.find('input[name="orderQuantity"]').val() || 1);
                tr.find('input[name="amount"]').val((unitPrice * quantity).toFixed(2));
            }
        });

        //监听提交
        form.on('submit(component-form-element)', function (data) {
            // 收集产品明细数据
            var products = [];
            $('#productTable tbody tr').each(function() {
                var row = $(this);
                products.push({
                    productCode: row.find('input[name="productCode"]').val(),
                    productName: row.find('input[name="productName"]').val(),
                    material: row.find('input[name="material"]').val(),
                    color: row.find('input[name="color"]').val(),
                    orderQuantity: parseInt(row.find('input[name="orderQuantity"]').val()),
                    unitQuantity: row.find('input[name="unitQuantity"]').val(),
                    amount: parseFloat(row.find('input[name="amount"]').val()),
                    orderGoodsTime: data.field.orderDate,
                    deliveryTime: data.field.deliveryDate
                });
            });

            var formData = {
                id: data.field.id,
                orderCode: data.field.orderCode,
                orderName: data.field.orderName,
                customerCode: data.field.customerCode,
                customerName: data.field.customerName,
                orderDate: new Date(data.field.orderDate).toISOString(),
                deliveryDate: new Date(data.field.deliveryDate).toISOString(),
                settlementMethod: data.field.settlementMethod,
                orderCategory: data.field.orderCategory,
                salesperson: data.field.salesperson,
                qualityRequirement: data.field.qualityRequirement,
                remark: data.field.remark,
                products: products
            };

            $.ajax({
                url: '/SalesOrder/Update',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(formData),
                success: function (res) {
                    if (res.code === 0) {
                        layer.msg(res.msg, {
                            icon: 1,
                            time: 2000
                        }, function () {
                            location.href = '/SalesOrder/Index';
                        });
                    } else {
                        layer.msg(res.msg, {
                            icon: 2,
                            time: 2000
                        });
                    }
                },
                error: function () {
                    layer.msg('服务器错误', {
                        icon: 2,
                        time: 2000
                    });
                }
            });
            return false;
        });
    });
</script> 